package com.eeepay.eeepay_v2.util;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.eeepay.eeepay_v2.app.MyApplication;
import com.eeepay.eeepay_v2.sqlite.DBHelper;
import com.eeepay.v2_library.log.LogUtils;


/**
 * Created by zw on 2016/4/1 0001.
 *      表中三个字段  _id、 user_id  、 news_id  判断消息是否未读
 */
public class DBUtils {

    /**
     * 插入数据
     * @param cv  ContentValues以键值对的形式存放数据
     */
    public static void insert(ContentValues cv){
        SQLiteDatabase database = MyApplication.dbHelper.getWritableDatabase();
        long insert = database.insert(DBHelper.NEWS_TABLE_NAME, null, cv);
        if(insert != -1){
            LogUtils.d("---------插入成功---------");
        }
        database.close();
    }

    /**
     * 查询是否存在
     * @param userId
     * @param newsId
     * @return
     */
    public static boolean query(String userId, String newsId){
//        LogUtils.d("---查询-------news_id = "+ newsId);
        boolean isHas = false;
        SQLiteDatabase database = MyApplication.dbHelper.getReadableDatabase();
        String sql = "select * from " + DBHelper.NEWS_TABLE_NAME
                + " where user_id = " + userId + " and news_id = " + newsId;
        Cursor cursor = database.rawQuery(sql, null);
//        database.query
//        Cursor cursor = database.query(DBHelper.NEWS_TABLE_NAME, null,
//                "user_id = ? and news_id = ?", new String[]{userId, newsId}, null, null, null);
//        LogUtils.d("---查询-----count--" + cursor.getCount());
        if(cursor.getCount() > 0){
           isHas = true;
        }
        database.close();
        return isHas;
    }

    /**
     * 删除
     * @param userId
     * @param newsId
     */
    public static void deleteById(String userId, String newsId){
//        LogUtils.d("---删除-------news_id = "+ newsId);
        SQLiteDatabase database = MyApplication.dbHelper.getWritableDatabase();
        int delete = database.delete(DBHelper.NEWS_TABLE_NAME,
                "user_id = ? and news_id = ?", new String[]{userId, newsId});
//        LogUtils.d("--删除---------delete--" + delete);
        database.close();
    }

    /**
     table：表名称
     colums：列名称数组
     selection：条件子句，相当于where
     selectionArgs：条件语句的参数数组
     groupBy：分组
     having：分组条件
     orderBy：排序类
     limit：分页查询的限制
     Cursor：返回值，相当于结果集ResultSet
     */
}
